var api = require('../config/api.js');

var isTokening = false;


function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
  //  + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "POST" ,loading=false , header = "application/json") {
  // console.log("loading");
  console.log(url);
  if (loading) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
  }
  return new Promise(function(resolve, reject) {
    var that = this;
    let token = wx.getStorageSync('token') || '';
    let isOld = true;

    if (url.indexOf('getdata') > -1) {
        console.log('存在吗')
        isOld = false;
    }
    console.log('token==' + token)
    console.log(url)
    console.log(method)
    wx.request({
      url: url,
      data: JSON.stringify(data),
      method: method,
      header: isOld== false ? {
        'Content-Type': header
      } : {
        'Content-Type': header,
        'Authorization' : token == '' ? '' : "Bearer " + token
      },
      success: async function(res) {
        if (res.statusCode == 200) {
          let code = res.data.code;
          console.log("code==" + code)
          if (code == 401) {
            wx.removeStorageSync('token');
            wx.removeStorageSync('openId');
            wx.removeStorageSync('headimg');
            wx.removeStorageSync('nickname');
            // 因为首页不需要登录
            if ((url.indexOf(api.getStudentgrades) > -1)) {
                return
            }
            wx.navigateTo({
                url: '/pages/login/login',
            })
            return
          }
          console.log(res.data)
          resolve(res.data);
        } else {
          reject(res.errMsg);
        }
      },
      fail: function(err) {
        reject(err)
      },
      complete: function () {
        if (loading) {
          wx.hideLoading();
        }
      }
    })
  });
}


/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function(resolve, reject) {
    wx.checkSession({
      success: function() {
        resolve(true);
      },
      fail: function() {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function getToken() {
  return new Promise(function(resolve, reject) {
    wx.login({
      success: function(res) {
        if (res.code) {
          console.log('走了吗')
          console.log(res.code)
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function(err) {
        reject(err);
      }
    });
  });
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    // image: '/static/images/icon_error.png',
    mask: true
  })
}

function showSuccessToast(msg) {
  wx.showToast({
    title: msg,
    mask: true
  })
}
function showToast(msg) {
  wx.showToast({
    title: msg,
    icon: 'none',
    mask: true
  })
} 
function floatAdd(arg1, arg2) {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split(".")[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2));
  n = (r1 >= r2) ? r1 : r2;
  return ((arg1 * m + arg2 * m) / m).toFixed(n);
}
//减    
function floatSub(arg1, arg2) {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split(".")[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split(".")[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2));
  //动态控制精度长度    
  n = (r1 >= r2) ? r1 : r2;
  return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
//乘    
function floatMul(arg1, arg2) {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split(".")[1].length
  } catch (e) { }
  try {
    m += s2.split(".")[1].length
  } catch (e) { }
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}  
function floatDiv(arg1, arg2) {
  var t1 = 0,
    t2 = 0,
    r1, r2;
  try {
    t1 = arg1.toString().split(".")[1].length
  } catch (e) { }
  try {
    t2 = arg2.toString().split(".")[1].length
  } catch (e) { }

  r1 = Number(arg1.toString().replace(".", ""));

  r2 = Number(arg2.toString().replace(".", ""));
  return (r1 / r2) * Math.pow(10, t2 - t1);
}
var dtime = '_deadtime';
function put(k, v, t) {
  wx.setStorageSync(k, v)
  var seconds = parseInt(t);
  if (seconds > 0) {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000 + seconds;
    wx.setStorageSync(k + dtime, timestamp + "")
  } else {
    wx.removeStorageSync(k + dtime)
  }
}

function get(k, def) {
  var deadtime = parseInt(wx.getStorageSync(k + dtime))
  if (deadtime) {
    if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
      console.log(def)
      return def;
    } else {
      var res = wx.getStorageSync(k);
      console.log(res)
      if (res) {
        return res;
      } else {
        return def;
      }
    }
  }
}

function remove(k) {
  wx.removeStorageSync(k);
  wx.removeStorageSync(k + dtime);
}

function clear() {
  wx.clearStorageSync();
}
function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}
module.exports = {
  formatTime,
  request,
  showErrorToast,
  showSuccessToast,
  showToast,
  checkSession,
  floatAdd,
  floatSub,
  floatMul,
  floatDiv,
  put,
  get,
  remove,
  clear,
  debounce
}